package com.du.ichat.fragment;


import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.du.ichat.R;
import com.du.ichat.UserInfoActivity;
import com.du.ichat.adapter.ContactAdapter;
import com.du.ichat.utils.SpUtils;
import com.du.ichat.view.SideBar;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.friend.FriendService;
import com.netease.nimlib.sdk.friend.FriendServiceObserve;
import com.netease.nimlib.sdk.friend.model.AddFriendNotify;
import com.netease.nimlib.sdk.friend.model.FriendChangedNotify;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.constant.SystemMessageType;
import com.netease.nimlib.sdk.msg.model.SystemMessage;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class ContactFragment extends Fragment {
    private TextView tvCenter;
    private SideBar sideBar;
    private RecyclerView recyclerView;
    private List<NimUserInfo> datas = new ArrayList<>();
    private ContactAdapter adapter;
    public ContactFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact, container, false);
        sideBar = view.findViewById(R.id.sideBar);
        tvCenter = view.findViewById(R.id.tvcenter);
        sideBar.setTextView(tvCenter);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new ContactAdapter(datas);
        recyclerView.setAdapter(adapter);
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                recyclerView.scrollToPosition(adapter.getPositionForFirstSpellAscii(s.charAt(0)) +1 );
            }
        });

        adapter.setContactItemClickListener(new ContactAdapter.OnContactItemClickListener() {
            @Override
            public void click(String string) {
                Intent intent = new Intent(getActivity() , UserInfoActivity.class);
                intent.putExtra("account" , string);
                startActivity(intent);
            }
        });

        adapter.setHeaderItemClickListener(new ContactAdapter.onHeaderItemClickListener() {
            @Override
            public void click(int position) {
                Log.e("tag" , "position : " + position);
            }
        });
        return view;
    }

    private void getFriends(){
        List<String> friends = NIMClient.getService(FriendService.class).getFriendAccounts();
        NIMClient.getService(UserService.class).fetchUserInfo(friends)
                .setCallback(new RequestCallback<List<NimUserInfo>>() {
                    @Override
                    public void onSuccess(List<NimUserInfo> nimUserInfos) {
                        ArrayList<NimUserInfo> list = new ArrayList<>();
                        list.addAll(nimUserInfos);
                        SpUtils.putObject(getActivity() , "friends" , list);
                        datas.clear();
                        datas.addAll(nimUserInfos);
                        for(NimUserInfo user : nimUserInfos){
                            Log.e("tag" , user.getAccount() + ":::" + user.getName());
                        }
                        adapter.setDatas(datas);
                    }

                    @Override
                    public void onFailed(int i) {

                    }

                    @Override
                    public void onException(Throwable throwable) {

                    }
                });
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        registOberve();
        getFriends();
    }



    private Observer<FriendChangedNotify> friendChangedNotifyObserver = new Observer<FriendChangedNotify>() {
        @Override
        public void onEvent(FriendChangedNotify friendChangedNotify) {
            getFriends();
        }
    };

    private void registOberve(){
        NIMClient.getService(SystemMessageObserver.class).observeReceiveSystemMsg(systemMessageObserver, true);
        NIMClient.getService(FriendServiceObserve.class).observeFriendChangedNotify(friendChangedNotifyObserver, true);

    }


    private Observer<SystemMessage> systemMessageObserver = new Observer<SystemMessage>() {
        @Override
        public void onEvent(SystemMessage message) {
            if (message.getType() == SystemMessageType.AddFriend) {
                AddFriendNotify attachData = (AddFriendNotify) message.getAttachObject();
                if (attachData != null) {
                    // 针对不同的事件做处理
                    if (attachData.getEvent() == AddFriendNotify.Event.RECV_ADD_FRIEND_DIRECT) {
                        // 对方直接添加你为好友
                    } else if (attachData.getEvent() == AddFriendNotify.Event.RECV_AGREE_ADD_FRIEND) {
                        // 对方通过了你的好友验证请求
                    } else if (attachData.getEvent() == AddFriendNotify.Event.RECV_REJECT_ADD_FRIEND) {
                        // 对方拒绝了你的好友验证请求
                    } else if (attachData.getEvent() == AddFriendNotify.Event.RECV_ADD_FRIEND_VERIFY_REQUEST) {
                        // 对方请求添加好友，一般场景会让用户选择同意或拒绝对方的好友请求。
                        // 通过message.getContent()获取好友验证请求的附言
                    }
                }
            }
        }
    };

}
